package com.tsingteng.cosfun.ui.costar;

import android.content.Intent;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.qiniu.pili.droid.shortvideo.PLDisplayMode;
import com.qiniu.pili.droid.shortvideo.PLShortVideoEditor;
import com.qiniu.pili.droid.shortvideo.PLShortVideoRecorder;
import com.qiniu.pili.droid.shortvideo.PLVideoEditSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoPlayerListener;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BaseActivity;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.utils.ConversionUtils;
import com.tsingteng.cosfun.utils.DateUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.TimeUtils;
import com.tsingteng.cosfun.utils.VideoUtils;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 描述 :
 * 创建人: 肖利.
 * 时间:2018/8/17
 * qq(872179966)
 */

public class ComposeVideoActivity extends BaseActivity implements PLVideoPlayerListener {
    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.preview)
    GLSurfaceView mPreview;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.record_progressbar)
    ProgressBar recordProgressbar;
    @BindView(R.id.lineView)
    LinearLayout mLineView;
    @BindView(R.id.iv_play)
    ImageView mIvPlay;
    @BindView(R.id.hs_pian_duan)
    HorizontalScrollView mHorizontal;
    private static final String TAG = "ComposeVideoActivity";
    private String mPathMp4;
    private long time = 0;
    private PLVideoEditSetting setting;
    private PLShortVideoEditor mShortVideoEditor;
    private long mMixDuration;
    private PLShortVideoEditorStatus mShortVideoEditorStatus = PLShortVideoEditorStatus.Idle;
    private Timer timerTask;
    private TimerTask taskTimer;
    private ArrayList<Long> videoTimeList;
    private long times = 0;
    private int index = 0;
    private boolean isStart = true;
    @Override
    protected void initView() {
        videoTimeList = VideoHelper.getIntence().getVideoTimeList();
        initRv();
        initShortVideoEditor();
        startPlayback();
    }

    private void initRv() {
        for (int i = 0; i < videoTimeList.size(); i++) {
            TextView textView = new TextView(this);
            textView.setTextSize(12);
            textView.setGravity(Gravity.CENTER);
            LinearLayout.LayoutParams textlayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            textlayoutParams.rightMargin = ConversionUtils.dip2px(this, 10f);
            textlayoutParams.leftMargin = ConversionUtils.dip2px(this, 10f);
            textView.setLayoutParams(textlayoutParams);
            textView.setText("" + (i + 1));
            textView.setBackground(getResources().getDrawable(R.drawable.selector_round_bg));
            if (i == 0) {
                textView.setSelected(true);
                textView.setTextColor(getResources().getColor(R.color.text_color_5));
            } else {
                textView.setTextColor(getResources().getColor(R.color.text_color_4));
                textView.setSelected(false);
            }
            mLineView.setGravity(Gravity.CENTER);
            mLineView.setOrientation(LinearLayout.HORIZONTAL);
            mLineView.addView(textView);
        }

    }


    public void rollBackLineView() {
        for (int i = 0; i < mLineView.getChildCount(); i++) {
            TextView childAt = (TextView) mLineView.getChildAt(i);
            childAt.setSelected(false);
            LinearLayout.LayoutParams textlayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            textlayoutParams.rightMargin = ConversionUtils.dip2px(this, 10f);
            textlayoutParams.leftMargin = ConversionUtils.dip2px(this, 10f);
            childAt.setLayoutParams(textlayoutParams);
            childAt.setTextColor(getResources().getColor(R.color.text_color_4));
        }
    }

    /**
     * 预览配置参数
     */
    private void initShortVideoEditor() {
        LogUtils.i("videoTimeListComposeVideoActivity" + videoTimeList.size());
        setting = new PLVideoEditSetting();
        setting.setSourceFilepath(mPathMp4);
        setting.setDestFilepath(VideoUtils.EDITED_FILE_PATH);
        mShortVideoEditor = new PLShortVideoEditor(mPreview, setting);
        mMixDuration = mShortVideoEditor.getDurationMs();
        LogUtils.i("videoTimeListComposeVideoActivity" + mMixDuration);
        mShortVideoEditor.setVideoPlayerListener(this);
        mShortVideoEditor.setDisplayMode(PLDisplayMode.FULL);
        recordProgressbar.setMax((int) (mMixDuration));
        times = VideoHelper.getIntence().getVideoTimeByIndex(0);
        startTimer();
    }

    private void startTimer() {
        timerTask = new Timer();
        taskTimer = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    LogUtils.e("tag");
                    time = time + 10;
                    if (tvTime != null)
                        tvTime.setText(DateUtils.div(time,1000,1)+ "s");
                    if (time >= times) {
                        if (index == 0)
                            if (mHorizontal ==null) return;
                            mHorizontal.fullScroll(ScrollView.FOCUS_AFTER_DESCENDANTS);
//                            ToastUtils. (index + "段完成");
                        if (index == videoTimeList.size() - 1) return;
                        addTimes();
                        changeUI(index);
                    }
                    if (recordProgressbar != null)
                        recordProgressbar.setProgress((int) time);
                });
            }
        };
        timerTask.schedule(taskTimer, 0, 10);
    }

    public void changeUI(int index) {
        rollBackLineView();
        TextView childAt = (TextView) mLineView.getChildAt(index);
        if (childAt==null)return;
        childAt.setTextColor(getResources().getColor(R.color.text_color_5));
        childAt.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams textlayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        textlayoutParams.rightMargin = ConversionUtils.dip2px(this, 10f);
        textlayoutParams.leftMargin = ConversionUtils.dip2px(this, 10f);
        childAt.setLayoutParams(textlayoutParams);
        childAt.setLayoutParams(textlayoutParams);
        childAt.setSelected(true);
    }

    public void addTimes() {
        index++;
        if (videoTimeList != null && videoTimeList.size() > index)
            times = times + videoTimeList.get(index);
    }

    /**
     * 启动预览
     */
    private void startPlayback() {
        mIvPlay.setVisibility(View.GONE);
        if (mShortVideoEditorStatus == PLShortVideoEditorStatus.Idle) {
            mShortVideoEditor.startPlayback();
            mShortVideoEditorStatus = PLShortVideoEditorStatus.Playing;
        } else if (mShortVideoEditorStatus == PLShortVideoEditorStatus.Paused) {
            mShortVideoEditor.resumePlayback();
            mShortVideoEditorStatus = PLShortVideoEditorStatus.Playing;
        }
    }

    /**
     * 停止预览
     */
    private void stopPlayback(boolean isClick) {
        if (isClick)
        mIvPlay.setVisibility(View.VISIBLE);
        mShortVideoEditor.stopPlayback();
        mShortVideoEditorStatus = PLShortVideoEditorStatus.Idle;
    }

    /**
     * 暂停预览
     */
    private void pausePlayback(boolean isClick) {
        if (isClick)
        mIvPlay.setVisibility(View.VISIBLE);
        mShortVideoEditor.pausePlayback();
        mShortVideoEditorStatus = PLShortVideoEditorStatus.Paused;
    }

    @Override
    public void onCompletion() {
        time = 0;
        index = 0;
        times = videoTimeList.get(0);
        changeUI(0);
        LogUtils.i("onCompletion");
    }


    @OnClick({R.id.preview, R.id.iv_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.preview:
                if (isStart) {
                    pausePlayback(true);
                    if (timerTask != null) {
                        timerTask.cancel();
                    }
                    if (taskTimer !=null) {
                        taskTimer.cancel();
                    }
                    timerTask = null;
                    taskTimer = null;
                } else {
                    startPlayback();
                    if (timerTask!= null) {
                        timerTask.cancel();
                    }

                    if (taskTimer !=null) {
                        taskTimer.cancel();
                    }
                    timerTask = null;
                    taskTimer = null;
                    startTimer();
                }
                isStart = !isStart;
                break;
            case R.id.iv_close:
                finish();
                overridePendingTransition(R.anim.activity_up_alpha, R.anim.activity_down);
                break;
        }
    }


    // 视频编辑器预览状态
    private enum PLShortVideoEditorStatus {
        Idle,
        Playing,
        Paused,
    }


    @Override
    protected void onResume() {
        super.onResume();
        startPlayback();
    }

    @Override
    protected void onPause() {
        super.onPause();
        pausePlayback(false);
        if (mShortVideoEditor != null) {
            mShortVideoEditor.pausePlayback();
        }
        if (taskTimer != null) {
            taskTimer.cancel();
            taskTimer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_compose_video;
    }

    @Override
    protected void getIntentData(Intent intent) {
        isFullScreen = true;
        mPathMp4 = intent.getStringExtra(VideoUtils.VIDEO_PATH);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(R.anim.activity_up_alpha, R.anim.activity_down);
    }
}
